const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors');
const router = require('koa-router')()

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
let intercept = async (ctx, next) => {
  if (ctx.request.method == "OPTIONS") {
    ctx.response.status = 200
  }
  await next()
}
app.use(intercept)

app.use(cors());
app.use(json())
app.use(logger())

// 公共路由
// const common = require('./routes/common_router/common')
// app.use(common.routes(), common.allowedMethods())

// routes
require('./routes/agk')(router)     // AGK

app.use(router.routes()).use(router.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app

